

define(['jquery', 'jquerymobile', 'net', 'md5','dialogs', 'newsroomDetailed', 'active'], function($, m, net, md5, dia, newsdetail, active) {
    // 当用户和密码输入都不为空的时候才激活登录按钮

    $('#btn_logon').attr("disabled","disabled");
    $('#logon_txt_username').on('input', function(evt){
        if ($(this).val().length > 0 && $('#logon_txt_password').val().length > 0) {
            $('#btn_logon').attr("disabled",false);
        } else {
            $('#btn_logon').attr("disabled","disabled");
        }
    });
    $('#logon_txt_password').on('input', function(evt){
        if ($('#logon_txt_username').val().length > 0 && $(this).val().length > 0) {
            $('#btn_logon').attr("disabled",false);
        } else {
            $('#btn_logon').attr("disabled","disabled");
        }
    });

    $('#scanQRCode').on('click', function() {
        cloudSky.zBar.scan(null, function(s) {
            console.assert(s != null, '扫描给回来的数据不对:%s', s);
            console.log('扫描结果:%s', s);
            net.post('user/activeQRCode', {
                code: s
            }, function(error){

            }, function(response){
                if (response.code == net.code.error) {
                    dia.alert('Oops!', response.msg, ['OK'], function(title) {

                    });
                } else if (response.code == net.code.countineActivity) {
                    active.showUser(response.data.userInfo);
                    $.mobile.newChangePage("#page_activation",{ transition: "slide",reverse: false,changeHash: false});
                } else {
                    console.assert(response.data != null, '扫描二维码后，服务器没有返回解码数据');
                    active.showUser(response.data.userInfo);
                    $.mobile.newChangePage("#page_activation",{ transition: "slide",reverse: false,changeHash: false});
                }
            });
        }, function(error) {
            console.error('扫描错误结果:%o', error);
        });

    });

    // 当点击登录按钮时候要做的事情
    $('#btn_logon').on ('click', function(evt){
        // 禁用按钮
        $('#btn_logon').attr("disabled","disabled");

        console.log(localStorage['username']);
        net.post('user/loginUser', {
            userName: $('#logon_txt_username').val(),
            password: md5.md5($('#logon_txt_password').val()),
            udid:device.uuid
        }, function(error){
            // 启用按钮
            $('#btn_logon').attr("disabled",false);
        }, function(response){
            q['user'] = response.data.user;
            // 启用按钮
            $('#btn_logon').attr("disabled",false);
            if (response.code != 0) {
                dia.alert('Oops!', response.msg, ['OK'], function(title) {

                });
            } else {
                //IBecon监听
//                monitorIBecon();

                //保存用户名
                localStorage.setItem('login_user', JSON.stringify(response.data.user));
                localStorage['username']=$('#logon_txt_username').val();
				chrome.storage.internal.set({'username':$('#logon_txt_username').val()}, function(data){if(data==0){console.log("Set username success!");}});
                $('#logon_txt_username').val("");
                $('#logon_txt_password').val("");
                $('#btn_logon').attr("disabled","disabled");

                //每次登录新用户 清空本地 tags 的存储
                localStorage['selected_tags'] = '';
                $.mobile.newChangePage("#newsroom",{ transition: "slide",reverse: false,changeHash: false});
            }
        });
    });

    var contrul = true;
    if (contrul) {
            //IBecon监听
            //monitorIBecon();
    }

    function monitorIBecon() {
        net.post('beacon/listBeacon',{
                'server':1
            } ,
            function(error){

            }, function(response){
                if (response.code != 0) {
                } else {
                    console.log('listBeacon:', response.data.beacon);
                    var beacons = [];
                    $.each(response.data.beacon, function(index, val){
                        var bacon = {};
                        bacon['proximityUUID'] =  val.proximityUUID;
                        bacon['major'] = val.major ;
                        bacon['minor'] = val.minor ;
                        bacon['identifier'] = val.major + val.minor;
                        bacon['in_distance'] = val.in_distance;
                        bacon['pop_up_message'] = val.pop_message;
                        beacons.push(bacon);
                    });
                    locateIbeaconas.checkIbeacon( beacons,
                        function(data) {
                            console.log(data);
                            getNews(data);
                            contrul = false;
                        },
                        function(error) {
                            console.error(error);
                        });
                }
            });
//        q['a'] = {aa:'xxx', bb: 'xxx'};
    }

    //获取新闻
    function getNews(data) {
        net.post('beacon/listNews',{
                'beacon.proximityUUID': data.proximityUUID,
                'beacon.major': data.major,
                'beacon.minor': data.minor
            },
        function(error) {

        }, function(response) {
                if(response.code != 0) {

                } else {
                    console.log(data.proximityUUID);
                    console.log(response.data);
                    if (response.data.news.length < 1)
                        return;

                    findNewBeacon(data, response.data.news, function(news) {
                        // noticifation user
                        console.log('弹出的新闻：');
                        console.log(news);
                        if (q['user'] != null) {
                            newsdetail.showDetailWithNews(news);
                            $.mobile.newChangePage("#newsroom_detailed",{ transition: "slide",reverse: false,changeHash: false});
                        } else {
                            newsdetail.showDetailWithNews(news);
                            $.mobile.newChangePage("#logon",{ transition: "slide",reverse: false,changeHash: false});
                        }
                    });
                }
            });
    }

    /**
     * 寻找新Beacon
     {
       "cache_beacons_news": [
         {
           "beacon": {
             "proximityUUID": "xxx",
             "major": "000000",
             "minor": "000000",
             "identify": "xxx000000000000"
           },
           "news": {
             "news_id": "",
             "title": "",
             "content": ""
           },
           "update_time": 0
         },
         ...
       ]
     }
     * @param beacon
     * @param news
     */
    function findNewBeacon(beacon, news, findNewCallback) {
        console.assert(news != null ,'news不能为空');
        console.assert((news.constructor+'').match('Object'), 'news必须为字典');
        chrome.storage.local.get('cache_beacons_news', function(val) {
            var needDelIndex = null;
            if (!$.isEmptyObject(val.cache_beacons_news)) {
                $.each(val.cache_beacons_news, function(index, beacon_new) {
                    if (beacon_new.beacon.proximityUUID == beacon.proximityUUID
                        && beacon_new.beacon.major == beacon.major
                        && beacon_new.beacon.minor == beacon.minor) {
                        console.log('beacon对应的信息');
                        if (beacon_new.news.news_id == news.news_id) {
                            if ((new Date().getTime()/1000) - beacon_new.update_time > 3 * 3600) {
                                beacon_new.update_time = new Date().getTime() / 1000;
                                if ($.isFunction(findNewCallback)) {
                                    console.log('新闻相同，三天后再次显示');
                                    findNewCallback(news);
                                }
                            }
                            return;
                        } else {
                            // 标记哪个需要被删除
                            needDelIndex = index;
                            if ($.isFunction(findNewCallback)) {
                                console.log('新闻不同:');
                                console.log(news);
                                findNewCallback(news);
                            }
                        }
                    }
                });
                // 删除
                val.cache_beacons_news.splice(needDelIndex,1);
                // 添加
                var iBeacon_news = {'beacon' : beacon,'news' : news,'update_time':new Date().getTime() / 1000 };
                val.cache_beacons_news.push(iBeacon_news);
                console.log(val.cache_beacons_news);
                if (!$.isEmptyObject(needDelIndex)) {
                    console.log(1111);
                    chrome.storage.local.set({'cache_beacons' : val.cache_beacons_news});
                }
            } else {
                var cache_beacons_news = [];
                // 添加
                var iBeacon_news = {'beacon' : beacon,'news' : news,'update_time':new Date().getTime() / 1000 };
                cache_beacons_news.push(iBeacon_news);
                chrome.storage.local.set({'cache_beacons' : cache_beacons_news});
                chrome.storage.local.get('cache_beacons',function(obj) {
                    console.log('新闻初次添加完成 查看结果');
                    console.log(obj.cache_beacons);
                });
                if ($.isFunction(findNewCallback)) {
                    findNewCallback(news);
                }
            }
        });
    }

    function compatibility() {
        /* Logon */
        $('#title_logon_on').parent()
            .css('display', 'block')
            .css('postion', 'relative');

        $('#title_logon_on').css('postion', 'absulute')
            .css('width', '60px')
            .css('height','20px')
            .css('margin', '8px auto auto auto');
    }

    $(document).ready(function () {
        setTimeout(function() {
            window.setBodyOverflow($(document.body));
            $('#logon_content').css('height',($(window).height()-40));
            $('#loading_page').css('display', 'none');
            $('.input').css({'border':'solid 1px #D2D2D2'});
            // 兼容其他浏览器
            compatibility();
//            hiddenSplash();
        },1000);

        setTimeout(function(){
            hiddenSplash();
			
            //IBecon监听
            monitorIBecon();
        }, 3000);
    });

    function hiddenSplash() {
        $('#loading_page').css('display', 'none');
        splash.hidden(null, function(){
            console.log('显示出来啦');
        }, function(){
            console.error('显示不出来啦');
        });
    }

    //设置内容高度是Header剩下的高度
    $("#logon").on( "pageshow", function( event ) {
		chrome.storage.internal.get("username", function(data){
			if(data.username){
				$('#logon_txt_username').val(data.username);
			}else if(localStorage['username']){
				$('#logon_txt_username').val(localStorage['username']);
			}else{
				$('#logon_txt_username').val("");
			}
		});
		$('#btn_logon').attr("disabled","disabled");
        $('#logon_txt_password').val("");       

        // 点击info按钮
        $('#btn_logon_infomation').off('click').
            on('click', function() {
                window.q['infomation_back'] = '#logon';
                $.mobile.newChangePage("#infomation",{ transition: "slide",reverse: false,changeHash: false});
        });
		
		window.historyView = [];
    });
});